import React, { useCallback, ReactNode } from "react";
import { createRoot } from "react-dom/client";
import type { ButtonProps } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import Modal from "@/components/Modal";
import CommonDisplayPanel from "@/components/CommonDisplayPanel";
import styles from "./useConfirm.module.css";

interface ConfirmOptions {
  /** 标题 */
  title?: ReactNode;
  /** 内容 */
  content?: ReactNode;
  /** 确认描述文本 (用于CommonDisplayPanel) */
  description?: string;
  /** 图标名称 (用于CommonDisplayPanel) */
  svgIcon?: string;
  /** 图标大小 (用于CommonDisplayPanel) */
  imageSize?: number;

  /** 是否为危险操作 */
  danger?: boolean;

  /** 宽度 */
  width?: number | string;

  /** 点击蒙层是否允许关闭 */
  maskClosable?: boolean;
  /** 自定义className */
  className?: string;
  /** 确定按钮属性 */
  okButtonProps?: ButtonProps;
  /** 自定义对话框属性 */
  modalProps?: Omit<
    React.ComponentProps<typeof Modal>,
    "visible" | "onOk" | "onCancel"
  >;
  /** 对齐方式 (用于CommonDisplayPanel) */
  align?: "center" | "left"; // 新增对齐方式属性
}

interface ConfirmModalProps extends ConfirmOptions {
  visible: boolean;
  onOk: () => void;
  onCancel: () => void;
}

/**
 * 确认对话框组件
 */
const ConfirmModal: React.FC<ConfirmModalProps> = ({
  title,
  content,
  description,
  svgIcon, // 默认图标
  imageSize = 80,
  width = 500,
  onOk,
  onCancel,
  className,
  okButtonProps = {},
  modalProps = {},
  danger,
  align = "left", // 左对齐
}) => {
  // 渲染内容区域
  const renderContent = () => {
    // 如果提供了自定义内容，则使用自定义内容
    if (content) {
      return <div className={styles.content}>{content}</div>;
    }

    // 否则使用 CommonDisplayPanel 组件
    return (
      <div className={styles.panelContainer}>
        <CommonDisplayPanel
          svgIcon={svgIcon}
          title={typeof title === "string" ? title : "确认操作"}
          description={description || "请确认是否继续此操作？"}
          imageSize={imageSize}
          align={align} // 左对齐
        />
      </div>
    );
  };

  return (
    <Modal
      visible={true}
      onOk={onOk}
      onCancel={onCancel}
      width={width}
      className={`${styles.confirmModal} ${className || ""}`}
      centered
      closable
      okButtonProps={{
        ...okButtonProps,
        danger,
      }}
      enableFooterBackground={false} // 禁用底部背景色
      {...modalProps}
    >
      {renderContent()}
    </Modal>
  );
};

/**
 * 确认对话框Hook
 *
 * @example
 * ```tsx
 * const confirm = useConfirm();
 *
 * const handleDelete = async () => {
 *   try {
 *     await confirm({
 *       title: '确认删除',
 *       content: '删除后无法恢复，确定要删除吗？',
 *       okText: '删除',
 *       danger: true
 *     });
 *     // 用户点击了确认
 *     message.success('删除成功');
 *   } catch (e) {
 *     // 用户点击了取消或关闭
 *     console.log('用户取消操作');
 *   }
 * };
 * ```
 */
const useConfirm = () => {
  return useCallback((options: ConfirmOptions = {}): Promise<void> => {
    return new Promise((resolve, reject) => {
      const div = document.createElement("div");
      document.body.appendChild(div);
      const root = createRoot(div);

      let currentOptions = {
        ...options,
        okButtonLoading: false,
      };

      const render = (props: typeof currentOptions) => {
        root.render(
          <ConfirmModal
            {...props}
            visible={true}
            onOk={async () => {
              // 设置确认按钮loading状态
              currentOptions = {
                ...currentOptions,
                okButtonLoading: true,
              };
              render(currentOptions);

              try {
                // 执行确认逻辑
                resolve();
                // 延迟关闭以展示loading效果
                setTimeout(() => {
                  root.unmount();
                  document.body.removeChild(div);
                }, 300);
              } catch {
                // 恢复按钮状态，但保持对话框开启
                currentOptions = {
                  ...currentOptions,
                  okButtonLoading: false,
                };
                render(currentOptions);
              }
            }}
            onCancel={() => {
              root.unmount();
              document.body.removeChild(div);
              reject(new Error("用户取消操作"));
            }}
          />
        );
      };

      render(currentOptions);
    });
  }, []);
};

export default useConfirm;
